<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="Resource Name" v-model="listQuery.filterItem">
      </el-input>
      <el-button class="filter-item" type="primary"  icon="el-icon-search" @click="handleFilter">search</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="goAddPage" type="primary" icon="el-icon-edit">add</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleShowTempList" type="primary" icon="el-icon-edit">showTemp</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='Index' width="95">
        <template slot-scope="scope">
          {{ 1 + scope.$index + ((listQuery.page -1 ) * listQuery.limit) }}
        </template>
      </el-table-column>
      <el-table-column label="Resource Name">
        <template slot-scope="scope">
          {{scope.row.resources_name}}
        </template>
      </el-table-column>
      <el-table-column label="Idle Amount" width="150" align="center">
        <template slot-scope="scope">
          {{scope.row.idle_amount}}
        </template>
      </el-table-column>
      <el-table-column label="Unit" width="150" align="center">
        <template slot-scope="scope">
          {{scope.row.unit}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Type" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.type}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="Price" width="110">
        <template slot-scope="scope">
          <span>{{scope.row.price}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="Actions" label="Display_time" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleShowTempResouce(scope.$index)">add
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogTableVisible">
      
    <el-table :data="tempResourceList" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='Index' width="95">
        <template slot-scope="scope">
          {{ 1 + scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="Resource Name">
        <template slot-scope="scope">
          {{scope.row.resources_name}}
        </template>
      </el-table-column>
      <el-table-column label="Amount" width="100" align="center">
        <template slot-scope="scope">
          {{scope.row.quantity}}
        </template>
      </el-table-column>
      <el-table-column label="Unit" width="80" align="center">
        <template slot-scope="scope">
          {{scope.row.unit}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Action" width="100">
        <template slot-scope="scope">
          <el-button @click="handleRemove(scope.$index)" size="mini" type="danger">remove
          </el-button>
        </template>
      </el-table-column>
    </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogTableVisible = false">Close</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="newTempResource" label-position="left" label-width="120px" style='width: 500px; margin-left:30px;'>
        <el-form-item label="Resource Name">
        <el-input disabled v-model="newTempResource.resources_name"></el-input>
      </el-form-item>
      <el-form-item label="Idle Amount">
        <el-input disabled v-model="newTempResource.idle_amount"></el-input>
      </el-form-item>
      <el-form-item label="Unit">
        <el-input disabled v-model="newTempResource.unit"></el-input>
      </el-form-item>
      <el-form-item label="Need Amount" prop="need_amount">
        <el-input type="number" v-model.number="newTempResource.need_amount"></el-input>
      </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false">Close</el-button>
        <el-button type="primary" @click="handleAddResource">Confirm</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getResourcesList } from '@/api/resource'

export default {
  data() {
    var checkNumber = (rule, value, callback) => {
          if (value <= 0) {
            callback(new Error('Amount must more than 0'));
          } else {
            callback();
          }
      };
    return {
      list: null,
      listLoading: true,
      tempResourceList: [],
      newTempResource: {
        resources_name: '',
        type: '',
        total_amount: '',
        price: '',
        unit: '',
        need_amount: ''
      },
      need_amountList: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        detail: 'Resources',
        add: 'Resource Need'
      },
      typeList: [{ 'type_name': 'Computer' }, { 'type_name': 'PC components' }],
      rules: {
        need_amount: [{ required: false, validator: checkNumber, trigger: 'blur' }]
      },
      total: null,
      listQuery: {
        page: 1,
        limit: 10,
        filterItem: null,
        type: null,
        status: null,
        sort: null
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }]
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  created() {
    if (this.$route.params.type == 'return') {
      this.tempResourceList = this.$route.params.tempResourceList
    }
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getResourcesList(this.listQuery).then(response => {
        this.list = response.dataList
        this.total = response.total
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleFilter() {
      this.getList()
    },
    goAddPage() {
      if(this.tempResourceList.length != 0) {
        this.$router.push({
          name: 'AddApplication',
          params: {
            'resourcesList': this.tempResourceList
          }
        })
      } else {
        this.$notify({
          title: 'Error',
          message: 'Please select more resources',
          type: 'error',
          duration: 2000
        })
      }
    },
    handleAddResource() {
      this.$refs['dataForm'].validate(valid => {
        if(valid){
          if(this.newTempResource.need_amount > this.newTempResource.idle_amount){
            this.$notify({
              title: 'Error',
              message: 'Amount can not more than idle amount',
              type: 'error',
              duration: 2000
            })
          } else {
          var temp = Object.assign({
            resources_id: this.newTempResource.resources_id,
            resources_name: this.newTempResource.resources_name,
            quantity: this.newTempResource.need_amount,
            unit: this.newTempResource.unit
          })
          if(this.need_amountList[temp.resources_id]==null){
            //此处需要取到新增这行的index
            this.tempResourceList.push(temp);
            this.need_amountList[temp.resources_id] = Object.assign({}, temp ,{
              index: this.tempResourceList.length-1
            })
            this.need_amountList[temp.resources_id].need_amount = Number(temp.quantity)
          } else {
            this.need_amountList[temp.resources_id].need_amount = Number(temp.quantity)
            this.tempResourceList[this.need_amountList[temp.resources_id].index].quantity = Number(temp.quantity)
          }
          this.dialogFormVisible = false
          }
        }
      })
    },
    handleShowTempList(){
      this.dialogStatus = 'detail'
      this.dialogTableVisible = true
    },
    handleRemove(index) {
      this.need_amountList[this.tempResourceList[index].resources_id]=null;
      this.tempResourceList.splice(index,1);
    },
    handleRemoveAll(){
      this.tempResourceList = [];
    },
    handleShowTempResouce(index){
      var tempAmount = 0;
      if(this.need_amountList[this.list[index].resources_id]!=null){
        tempAmount = this.need_amountList[this.list[index].resources_id].need_amount
      }
      this.newTempResource = Object.assign({}, this.list[index], { need_amount: Number(tempAmount) })
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    }
  }
}
</script>
